/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.security;

import org.springframework.security.crypto.codec.Utf8;

import com.legendshop.oa.util.MD5Util;

/**
 * 密码加密器，可以根据不同的条件来加解密
 */
public class PasswordEncoderImpl implements PasswordEncoder {

	/**
	 * 加密密码, 如果有不同的加密方法则只需要修改该方法
	 * rawPass: 密码
	 * salt： 加密因子,可有可无,直接MD5调用则不需要该参数
	 * 
	 */
	@Override
	public String encodePassword(String rawPass, Object salt) {
		return MD5Util.toMD5Password(salt.toString(), rawPass);
	}

	/**
	 * 检查密码是否相等
	 */
	@Override
	public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
        String pass1 = "" + encPass;
        String pass2 = encodePassword(rawPass, salt);
        return equals(pass1,pass2);	
	}

	
    /**
     * Constant time comparison to prevent against timing attacks.
     * @param expected
     * @param actual
     * @return
     */
    static boolean equals(String expected, String actual) {
        byte[] expectedBytes = bytesUtf8(expected);
        byte[] actualBytes = bytesUtf8(actual);
        int expectedLength = expectedBytes == null ? -1 : expectedBytes.length;
        int actualLength = actualBytes == null ? -1 : actualBytes.length;
        if (expectedLength != actualLength) {
            return false;
        }

        int result = 0;
        for (int i = 0; i < expectedLength; i++) {
            result |= expectedBytes[i] ^ actualBytes[i];
        }
        return result == 0;
    }
    
    private static byte[] bytesUtf8(String s) {
        if(s == null) {
            return null;
        }
        return Utf8.encode(s);
    }
    
    public static void main(String[] args) {
    	PasswordEncoderImpl encoderImpl=new PasswordEncoderImpl();
    	System.out.println(encoderImpl.encodePassword("a123456", "18588545465"));
	}


}
